<?php
/**
 * Created by PhpStorm.
 * User: ZNZG
 * Date: 2020/3/18
 * Time: 19:11
 */

namespace app\common\lib;

use app\common\exception\BaseException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class Token
{
    protected $payload;
    protected $config;
    protected $key;

    public function __construct($expire = 0)
    {
        $this->config = config('token');

        $this->payload = [
            "iss" => $this->config['iss'],
            "aud" => $this->config['aud'],
            "iat" => time()
        ];
        $this->key = $this->config['key'];
    }

    /**
     * 生成token
     * @param $infos
     * @param int $expire
     * @return string
     */
    public function encode($infos,$expire = 0)
    {
        $expire = intval($expire) > 0?$expire:$this->config['expire'];
        $this->payload['exp'] = time() + $expire;
        $this->payload['infos'] = $infos;

        return JWT::encode($this->payload,$this->key,'HS256');
    }

    /**
     * token解密
     * @param string $token
     * @return bool|object
     */
    public function decode($token = '')
    {
        try{
            return JWT::decode($token,new Key($this->key,'HS256'));
        } catch (\Exception $e) {
            // 记录日志
            return false;
        }
    }

    /**
     * 根据KEY获取相应的缓存值
     * @param $key
     * @return mixed
     * @throws BaseException
     */
    public function getCurrentTokenVar($key)
    {
        $token_decode = $this->decode(str_replace('Bearer ', '', request()->header('Authorization')));

        if(!isset($token_decode->infos))
        {
            throw new BaseException('无效Token');
        }
        else
        {
            $vars = $token_decode->infos;
            if(isset($vars->$key))
            {
                return $vars->$key;
            }
            else
            {
                throw new BaseException('尝试获取的TOKEN变量并不存在');
            }
        }
    }

    /**
     * 获取用户ID
     * @return mixed
     * @throws BaseException
     */
    public function getCurrentUid()
    {
        $uid = self::getCurrentTokenVar('uid');
        return $uid;
    }

    /**
     * 获取用户名称
     * @return mixed
     * @throws BaseException
     */
    public function getCurrentUname()
    {
        $uname = self::getCurrentTokenVar('uname');
        return $uname;
    }

    /**
     * 判断传入的UID是否有效
     * @param $checkUID
     * @return bool
     * @throws BaseException
     */
    public function isValidOperate($checkUID)
    {
        if(!$checkUID)
        {
            throw new BaseException('检查UID时必须传入一个UID');
        }

        return $checkUID == $this->getCurrentUid();
    }
}